package com.meilishuo.android.performance;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by victor on 14-9-5.
 */
public class MemInfo
{
    private static final Logger logger = LoggerFactory.getLogger(MemInfo.class);
    private static final String JSCHARTPATH = "target/android-info/mem/html/";
    private static final String MEMFILEPATH = "target/android-info/mem/dat/mem.dat";
    private static final String url = "http://agile.meiliworks.com/data_mgr/save/dashboard";
    private static final String runInfo="target/android-info/run-info.txt";
    private static final String jpgFile = "target/android-info/mem/html/mem.jpg";

    private static TreeMap<String, List<String>> memMap = new TreeMap<String, List<String>>();

    /**
     * 解析mem.dat存储到map中
     */
    public void parseMemFile()
    {
        File file = new File(MEMFILEPATH);
        if(null==file) return;

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = null;

            while((line=bufferedReader.readLine())!=null)
            {
                String result = line.trim();
                if(memMap.size()==0 || !memMap.containsKey("com.meilishuo"))
                {
                    List<String> memList = new ArrayList<String>();
                    memList.add(result);
                    memMap.put("com.meilishuo", memList);
                }
                else
                {
                    memMap.get("com.meilishuo").add(result);
                }
            }
            System.out.println(memMap.size());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将map中的数据写到到xml中
     */
    public void writeXmlFromMap()
    {
        if(null==memMap || memMap.size()==0)
            return;
        Iterator<String> it = memMap.keySet().iterator();
        while(it.hasNext())
        {
            String key = it.next();
            List<String> value = memMap.get(key);
            if(null==value || value.size()<=1)
                continue;
            //写入xml
            File file = new File(JSCHARTPATH+key.replace("/", "_").replace(":", "_")+"_mem.xml");
            try {
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
                bufferedWriter.write(
                        "<?xml version=\"1.0\"?>\n" +
                        "<JSChart>\n" +
                        "\t<dataset type=\"line\">");
                int pos = 1;
                for(String index : value)
                {
                    bufferedWriter.write("<data unit=\""+pos+"\" value=\""+index+"\"/>\n");
                    pos++;
                }
                bufferedWriter.write(
                        "</dataset>\n" +
                                "\t<optionset>\n" +
                                "\t\t<option set=\"setLineColor\" value=\"'#8D9386'\"/>\n" +
                                "\t\t<option set=\"setLineWidth\" value=\"4\"/>\n" +
                                "\t\t<option set=\"setTitleColor\" value=\"'#7D7D7D'\"/>\n" +
                                "\t\t<option set=\"setAxisColor\" value=\"'#9F0505'\"/>\n" +
                                "\t\t<option set=\"setGridColor\" value=\"'#a4a4a4'\"/>\n" +
                                "\t\t<option set=\"setAxisValuesColor\" value=\"'#333639'\"/>\n" +
                                "\t\t<option set=\"setAxisNameColor\" value=\"'#333639'\"/>\n" +
                                "\t\t<option set=\"setTextPaddingLeft\" value=\"0\"/>\n" +
                                "\t\t<option set=\"setLineSpeed\" value=\"100\"/>\n" +
                                "\t\t<option set=\"setBarSpeed\" value=\"100\"/>\n" +
                                "\t</optionset>\n " +
                        "</JSChart>");
                bufferedWriter.flush();
                bufferedWriter.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成jschart html文件
     */
    public void writeJsHtml()
    {
        if(null==memMap || memMap.size()==0)
            return;
        Iterator<String> it = memMap.keySet().iterator();
        while(it.hasNext())
        {
            String key = it.next();
            List<String> value = memMap.get(key);
            if(null==value || value.size()<=1)
                continue;
            File htmlFile = new File(JSCHARTPATH+key.replace("/", "_").replace(":", "_")+"_mem.html");
            try {
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(htmlFile));
                bufferedWriter.write(
                        "<html>\n" +
                                "<head>\n" +
                                "\n" +
                                "<title>JSChart</title>\n" +
                                "\n" +
                                "<script type=\"text/javascript\" src=\"http://www.jscharts.com/script/jscharts.js?v=3.0\"></script>\n" +
                                "\n" +
                                "</head>\n" +
                                "<body>\n" +
                                "<div id=\"result\">\n" +
                                "<h3>"+htmlFile.getName().replace(".xml", "")+"</h3>" +
                                "<div id=\"graph\">Loading graph...</div>\n" +
                                "\n" +
                                "<script type=\"text/javascript\">\n");

                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("var myData = new Array(");
                int pos = 1;
                for(String index : value)
                {
                    stringBuffer.append("[" + pos + ", " + index + "],");
                    pos++;
                }
                System.out.println(stringBuffer.toString());
                int startPos = stringBuffer.lastIndexOf(",");
                if(startPos==-1)
                {
                    stringBuffer.append(")");
                }
                else {
                    stringBuffer.replace(startPos, stringBuffer.length(), ");");
                }
                bufferedWriter.write(stringBuffer.toString());

                bufferedWriter.write("var myChart = new JSChart('graph', 'line');\n" +
                        "        myChart.setDataArray(myData);\n" +
                        "        myChart.setLineColor('#8D9386');\n" +
                        "        myChart.setLineWidth(4);\n" +
                        "        myChart.setTitleColor('#7D7D7D');\n" +
                        "        myChart.setAxisColor('#9F0505');\n" +
                        "        myChart.setGridColor('#a4a4a4');\n" +
                        "        myChart.setAxisValuesColor('#333639');\n" +
                        "        myChart.setAxisNameColor('#333639');\n" +
                        "        myChart.setTextPaddingLeft(0);\n" +
                        "        myChart.setBarSpeed(100);\n" +
                        "        myChart.setLineSpeed(100);\n" +
                        "        myChart.setSize(800, 400);\n" +
                        "        myChart.draw();\n" +
                        "\n" +
                        "</script>\n" +
                        "\n" +
                        "</body>\n" +
                        "</html>");
                bufferedWriter.flush();
                bufferedWriter.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void writeAllJsHtml()
    {
        File[] files = new File(JSCHARTPATH).listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith("_mem.html");
            }
        });
        if(files.length==0) return;

        File allHtmlFile = new File(JSCHARTPATH+"all_mem.html");
        if(allHtmlFile.exists())
            allHtmlFile.delete();

        try {
            allHtmlFile.createNewFile();
            BufferedWriter out = new BufferedWriter(new FileWriter(allHtmlFile, true));
            String header =
                    "<!DOCTYPE html>\n" +
                            "<html>\n" +
                            "<head lang=\"en\">\n" +
                            "    <meta charset=\"UTF-8\">\n" +
                            "    <title>内存变化趋势</title>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<h1> 内存变化趋势</h1>\n";
            out.write(header);


            for(File index : files)
            {
                String fileName = index.getName();

                out.write("<iframe src=\""+fileName+"\" width=\"100%\" height=\"500\"></iframe><br>\n");

            }

            out.write("</body>\n</html>");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算出最大值，最小值，平均值，然后推送到服务器
     */
    public void pushInfo2Server()
    {
        String sceneInfo = null;
        String startTime = null;
        String endTime = null;
        //读取运行信息
        File file = new File(runInfo);
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            sceneInfo = bufferedReader.readLine(); //第一行场景信息，monkey，静置等
            startTime = bufferedReader.readLine();  //第二行开始运行时间
            endTime = bufferedReader.readLine();  //第三行结束运行时间

        } catch (Exception e)
        {
            e.printStackTrace();
        }

        List<Double> cpuAllProcess = new ArrayList<Double>();
        Iterator<String> it = memMap.keySet().iterator();
        int pos = 0;
        while(it.hasNext()) {
            String key = it.next();
            List<String> value = memMap.get(key);
            int listPos = 0;
            for(String indexValue : value)
            {
                int cpuSlice = Integer.parseInt(indexValue);
                if( pos == 0 ) //第一次循环，直接将值付给cpuAllProcess
                {
                    cpuAllProcess.add(cpuSlice * 1.0);
                }
                else
                {
                    cpuAllProcess.set(listPos, cpuAllProcess.get(listPos) + cpuSlice);
                    listPos++;
                }
            }
        }

        Double memMin = 6000000.0;
        Double memMax = 0.0;

        //循环求最大值，最小值，平均值
        Double sum = 0.0;
        for(Double index : cpuAllProcess)
        {
            sum += index;
            if(memMin > index)
                memMin = index;
            if(memMax < index)
                memMax = index;
        }

        //生成图标
        JFreeChartUtil.generateChart(cpuAllProcess, jpgFile);

        //将图片推送到tomcat上
        String relativelyPath=System.getProperty("user.dir");
        String jpgFilePath = relativelyPath+File.separator+jpgFile;
        System.out.println(jpgFilePath);
        System.out.println(relativelyPath + File.separator + "src"+ File.separator + "main" + File.separator + "resources" + File.separator +"scp.sh ");
        String result = ShellUtil.execShellFile(relativelyPath + File.separator + "src"+ File.separator + "main" + File.separator + "resources" + File.separator +"scp.sh ", jpgFilePath);
        System.out.println(result);

        Double avg = sum / cpuAllProcess.size();

        HttpClient httpClient = HttpClients.createDefault();
        try {
            StringEntity stringEntity = new StringEntity("{\"env\":\"MOB\", \"type\":\"MEMORY\", \"scene\":\""+sceneInfo+"\", \"runStartTime\":\""+startTime+"\", \"runEndTime\":\""+endTime+"\", \"data\":{\"max\":"+memMax+", \"min\":"+memMin+", \"avg\":"+avg+", \"pic\":\""+Constant.tomcatUrl+"/mem.jpg"+"\"}}", "utf-8");
            System.out.println(EntityUtils.toString(stringEntity));
            HttpPost post = new HttpPost(url);
            post.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            post.setEntity(stringEntity);

            HttpResponse response = httpClient.execute(post);
            System.out.println(EntityUtils.toString(response.getEntity()));
            post.releaseConnection();

        } catch (Exception e)
        {
            e.printStackTrace();
        }


    }

    @Test
    public void generateMemHtmlInfo()
    {
        MemInfo memInfo = new MemInfo();
        memInfo.parseMemFile();
        pushInfo2Server();
        memInfo.writeXmlFromMap();
        memInfo.writeJsHtml();
        memInfo.writeAllJsHtml();
    }

}
